<?php

require_once(dirname(__FILE__).'/../../inc/config.inc.php');

  /*******************************************************
   * Only these origins will be allowed to upload images *
   ******************************************************/

  /*********************************************
   * Change this line to set the upload folder *
   *********************************************/
  $rootDir = '../../../';
  $time = date('Ymd',time());
  $imagePath = "uploads/image/".$time."/";
  $imageFolder = $rootDir.$imagePath;
  // Create target dir
  if (!file_exists($imageFolder)) {
    @mkdir($imageFolder);
  }

  // echo $imageFolder;
  // exit;

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){
    if (isset($_SERVER['HTTP_ORIGIN'])) {        
      header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
    }

    /*
      If your script needs to receive cookies, set images_upload_credentials : true in
      the configuration and enable the following two headers.
    */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})|^[\x{4e00}-\x{9fa5}]+$/u", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // Accept upload if there was no origin, or if it is an accepted origin
    $imgName = $_FILES["file"]["name"];
    $arr = explode('.',$imgName);
    if(is_array($arr)){
      $imgName = uniqid().'.'.$arr[1];
    }
    
    $filetowrite = $imageFolder . $imgName;
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    //添加数据库记录
    $sql = "INSERT INTO `#@__uploads` (name, path, size, type, posttime) VALUES ('$imgName', '".$imagePath.$imgName."', '".$_FILES["file"]["size"]."', '".$_FILES["file"]["type"]."', '".time()."')";
    $dosql->ExecNoneQuery($sql);

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}
    echo json_encode(array('location' => "../" . $imagePath . $imgName));
  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }
?>
